﻿using Enter.Dashboard.Api.Entities;
using Enter.Enums;
using Enter.Utils.JsonExt;
using FluentScheduler;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading;

namespace Enter.Dashboard.Api.Tasks
{
    public class NoticeJob : IJob
    {
        private int executionCount = 0;

        private readonly ILogger _logger;
        private readonly IFreeSql _fsql;
        private readonly IConfiguration _configuration;
        public NoticeJob(ILogger logger, IFreeSql fsql, IConfiguration configuration) 
        {
            _logger = logger;
            _fsql = fsql;
            _configuration = configuration;
        }

        public void Execute()
        {
            try
            {
                // SealOutTime 保全到期前45日提前  保全到期日/查封、冻结到期日
                // CourtTime   开庭提前10日提醒
                // RenewalTime 委托到期日前45日提醒 委托到期日/续聘到期日
                var currDate = DateTime.Now.Date;
                // 三十天提醒一次;

                var allNotice = (int)(EnumArchiveNoticed.SealOutTime45 | EnumArchiveNoticed.CourtTime10 | EnumArchiveNoticed.RenewalTime45);

                var SealOutTimes = new List<int> { allNotice, (int)(EnumArchiveNoticed.SealOutTime45 | EnumArchiveNoticed.CourtTime10), (int)(EnumArchiveNoticed.SealOutTime45 | EnumArchiveNoticed.RenewalTime45), (int)EnumArchiveNoticed.SealOutTime45 };
                var archives = _fsql.Select<Archive>().Where(t => t.SealOutTime.Date >= currDate && t.SealOutTime.Date <= currDate.AddDays(45) && !SealOutTimes.Contains(t.Noticed) && t.IsDeleted == false).ToList();
                foreach (var arc in archives)
                {
                    _fsql.Update<Archive>().Set(t => new { Noticed = t.Noticed | (int)EnumArchiveNoticed.SealOutTime45 }).Where(t => t.Id == arc.Id).ExecuteAffrows();
                    SendForArchive(arc, EnumArchiveNoticed.SealOutTime45);
                }

                var CourtTimes = new List<int> { allNotice, (int)(EnumArchiveNoticed.CourtTime10 | EnumArchiveNoticed.SealOutTime45), (int)(EnumArchiveNoticed.CourtTime10 | EnumArchiveNoticed.RenewalTime45), (int)EnumArchiveNoticed.CourtTime10 };
                archives = _fsql.Select<Archive>().Where(t => t.CourtTime.Date >= currDate && t.CourtTime.Date <= currDate.AddDays(10) && !CourtTimes.Contains(t.Noticed) && t.IsDeleted == false).ToList();
                foreach (var arc in archives)
                {
                    _fsql.Update<Archive>().Set(t => new { Noticed = t.Noticed | (int)EnumArchiveNoticed.CourtTime10 }).Where(t => t.Id == arc.Id).ExecuteAffrows();
                    SendForArchive(arc, EnumArchiveNoticed.CourtTime10);
                }

                var RenewalTimes = new List<int> { allNotice, (int)(EnumArchiveNoticed.RenewalTime45 | EnumArchiveNoticed.SealOutTime45), (int)(EnumArchiveNoticed.RenewalTime45 | EnumArchiveNoticed.CourtTime10), (int)EnumArchiveNoticed.RenewalTime45 };
                archives = _fsql.Select<Archive>().Where(t => t.RenewalTime.Date >= currDate && t.RenewalTime.Date <= currDate.AddDays(45) && !RenewalTimes.Contains(t.Noticed) && t.IsDeleted == false).ToList();
                foreach (var arc in archives)
                {
                    _fsql.Update<Archive>().Set(t => new { Noticed = t.Noticed | (int)EnumArchiveNoticed.RenewalTime45 }).Where(t => t.Id == arc.Id).ExecuteAffrows();
                    SendForArchive(arc, EnumArchiveNoticed.RenewalTime45);
                }

                var count = Interlocked.Increment(ref executionCount);
                _logger.LogInformation("定时任务服务运行. Count: {Count}", count);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "定时任务执行异常.");
            }
        }
        // SealOutTime 保全到期前45日提前  保全到期日/查封、冻结到期日
        // CourtTime   开庭提前10日提醒
        // RenewalTime 委托到期日前45日提醒 委托到期日/续聘到期日
        private void SendForArchive(Archive archive, EnumArchiveNoticed noticeType)
        {
            try
            {
                var title = string.Empty;
                var body = string.Empty;
                switch (noticeType) 
                {
                    case EnumArchiveNoticed.SealOutTime45:
                        title = "保全到期提醒";
                        body = string.Format("合同编号:{0}<br/>保全到期日:{1}", 
                            archive.ContractNo, 
                            archive.SealOutTime.ToString(DateFormatConverter.Format_yyyyMMdd)
                            );
                        break;
                    case EnumArchiveNoticed.CourtTime10:
                        title = "开庭日提醒";
                        body = string.Format("合同编号:{0}<br/>开庭日:{1}", 
                            archive.ContractNo,
                            archive.CourtTime.ToString(DateFormatConverter.Format_yyyyMMddHHmmss)
                            );
                        break;
                    case EnumArchiveNoticed.RenewalTime45:
                        title = "委托到期提醒";
                        body = string.Format("合同编号:{0}<br/>委托到期日:{1}",
                            archive.ContractNo,
                            archive.RenewalTime.ToString(DateFormatConverter.Format_yyyyMMdd)
                            );
                        break;
                }
                // 发送消息;
                _fsql.Insert<Notice>(new Notice
                {
                    Id = 0,
                    ToUserId = archive.ChargeUserId2,
                    CreateTime = DateTime.Now,
                    Note = body,
                    Title = title,
                    ObjectType = 1,
                    ObjectId = archive.Id,
                    NoticeType = (int)noticeType,
                    Readed = false,
                    UpdateTime = DateTime.Now,
                }).ExecuteAffrows();
                // 发送邮件;
                //var mailModel = _configuration.GetSection("Mail").Get<MailModel>();
                //mailModel.Send(title, body);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送消息和邮件异常.");
            }
        }
    }
}
